package com.example.mobile2021606127cxz0521;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private RecyclerView rv;
    String url = "http://192.168.1.103:3000/news";
    OkHttpClient okHttpClient = new OkHttpClient();
    Gson gson = new Gson();
    final Type type = new TypeToken<List<News>>() {
    }.getType();
    List<News> newsList = new ArrayList<>();
    NewsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rv = findViewById(R.id.rv);
        new Thread(() -> {
            Request request = new Request.Builder()
                    .url(url)
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {

                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    String result = response.body().string();
                    newsList = gson.fromJson(result, type);
                    Log.i("TAG", "onResponse: " + newsList.size());
                    adapter = new NewsAdapter(newsList);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            rv.setAdapter(adapter);
                        }
                    });
                }
            });
        }).start();

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rv.setLayoutManager(layoutManager);
    }
}